package org.example.algorithm.bst;

import org.example.algorithm.TreeNode;

import java.util.Stack;

public class KthSmallestSolution {

    //通过中序遍历找到第k个元素
    public int kthSmallest(TreeNode root, int k) {
        if (root == null) {
            return -1;
        }
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        int count = 0;
        while (!stack.isEmpty() || cur != null) {
            while (cur!=null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode node = stack.pop();
            count++;
            if (count == k) {
                return node.val;
            }
            cur = node.right;
        }
        return -1;
    }

    public static void main(String[] args) {

    }
}
